/**
 * 获取accessToken
 */
const fs = require('fs');
const request = require('../../util/request');
const accessConfig = require('../../config/baidu');
const BAIDU_ACCESS_HOST = 'aip.baidubce.com';
const BAIDU_ACCESS_PATH = '/oauth/2.0/token';
let accessJson = {};

const errorInfo = (...a)=> {
    console.error(...a);
}

const getAccessFromJson = () => {
    const {
        access_token : accessToken,
        expires_in : expiresIn,
        last_modified: lastModified 
       } = accessJson;
    if(accessToken && (expiresIn * 1000 + lastModified) > Date.now()) {
        return accessToken
    }
    return null;
}

 module.exports = () => {
     return new Promise((resolve, reject) => {
         let accessToken = getAccessFromJson();
         if(accessToken){
             return resolve(accessToken);
         }
         request.ajax({
             host : BAIDU_ACCESS_HOST,
             path : BAIDU_ACCESS_PATH,
             param : {
                 'grant_type' : accessConfig.GRANT_TYPE,
                 'client_id' : accessConfig.CLIENT_ID,
                 'client_secret' : accessConfig.CLIENT_SECRET
             }
         })
         .then((json) => {
            if(json.result == 0) {
                accessJson = json.data;
                accessJson['last_modified'] = Date.now();
                resolve(accessJson.access_token);
                return;
            }
            reject('获取token失败');
         })
         .catch(e => {
            errorInfo(e);
            reject('获取token异常');
         });
     });
 }